package com.mlizhi.modules.login;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.base.Utils;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.SpecActivity;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class AutoLoginActivity extends Activity {

	private Session mSession;
	private Context mContext;
	private RequestQueue mRequestQueue;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_auto);
		mContext = this;
		mSession = Session.get(getApplicationContext());
		/** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
		MobclickAgent.updateOnlineConfig( mContext );
		/** 设置是否对日志信息进行加密, 默认false(不加密). */
		AnalyticsConfig.enableEncrypt(true);
		autoLogin();
	}

	/**
	 * 登录
	 */
	private void autoLogin() {
		
		boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
		if (netUsable) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
			StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_USER_LOGIN_URL,
					listener4LoginSuccess,listener4LoginError ){
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {
					String timestamp = SecurityUtil.getTimestamp();
					Map<String, String>  params = new HashMap<String, String>();
					params.put("mobile", mSession.getAccount());
					params.put("password", mSession.getPassword());
					params.put("companyId", Constants.COMPANY_ID);
					params.put(Constants.URL_TIMESTAMP,timestamp );
					params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
					return params;
				}
			};
//	            stringRequest.setTag(TAG);
			stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, 1, 1.0f));
			mRequestQueue.add(stringRequest);
			mRequestQueue.start();
		}else {
			Toast.makeText(mContext,R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
			startActivity(new Intent(AutoLoginActivity.this,LoginActivity.class));
			AutoLoginActivity.this.finish();
		}
		return ;
	}
	
	Response.ErrorListener listener4LoginError = new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			Toast.makeText(mContext,error.getMessage(),Toast.LENGTH_SHORT).show();
		}
	};
	
	Response.Listener<String> listener4LoginSuccess = new Response.Listener<String>() {
		@Override
		public void onResponse(String response) {
			String code = JsonUtil.getHeaderCode(response);
			if(Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)){
				JSONObject bodyJsonObject = JsonUtil.getBodyJsonObject(response);
				try {
					
					JSONObject userJsonObject = bodyJsonObject.getJSONObject("customer");//用户信息的key
					String username = userJsonObject.getString("nikeName");
					if(username == null) username="";
					mSession.setUserName(username);
					mSession.setUid(userJsonObject.getString("id"));
					String headImgurl = userJsonObject.getString("headImgurl");
					if(headImgurl == null) headImgurl="";
					mSession.setUserIcon(headImgurl);
					String address = userJsonObject.getString("address");
					if(address == null) address="";
					mSession.setUserAddress(address);
					
				} catch (JSONException e) {
//	                    e.printStackTrace();
					Utils.E("parse login result info json string error!!!",e);
				}
				startActivity(new Intent(mContext,SpecActivity.class));
				AutoLoginActivity.this.finish();
			}else {
				Toast.makeText(mContext,JsonUtil.getHeaderErrorInfo(response),Toast.LENGTH_SHORT).show();
				startActivity(new Intent(AutoLoginActivity.this,LoginActivity.class));
				AutoLoginActivity.this.finish();
			}
		}
	};
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		MobclickAgent.onPause(this);
	}
	
}